import CryptoJS from 'crypto-js';

/**
 * 获取地址栏参数值
 * @param name
 * @returns {null}
 * @constructor
 */
export function GetQueryString (name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
  var r = window.location.search.substr(1).match(reg);
  var s = window.location.search;
  var href = window.location.href;
  var index = href.indexOf('?');
  if (s === '') {
    r = href.substr(index + 1).match(reg);
  }
  if (r != null) return unescape(r[2]);
  return null;
}
/**
 * 存储localStorage
 */
export const setStore = (name, content) => {
  if (!name) return;
  if (typeof content !== 'string') {
    content = JSON.stringify(content);
  }
  window.localStorage.setItem(name, content);
};

/**
 * 获取localStorage
 */
export const getStore = name => {
  if (!name) return;
  return window.localStorage.getItem(name);
};

/**
 * 删除localStorage
 */
export const removeStore = name => {
  if (!name) return;
  window.localStorage.removeItem(name);
};

// //获取登录
// export const  IsLogin =() =>{
//   return !!getStore('token')
// }
/**
 * 获取style样式
 */
export const getStyle = (element, attr, NumberMode = 'int') => {
  let target;
  // scrollTop 获取方式不同，没有它不属于style，而且只有document.body才能用
  if (attr === 'scrollTop') {
    target = element.scrollTop;
  } else if (element.currentStyle) {
    target = element.currentStyle[attr];
  } else {
    target = document.defaultView.getComputedStyle(element, null)[attr];
  }
  // 在获取 opactiy 时需要获取小数 parseFloat
  return NumberMode === 'float' ? parseFloat(target) : parseInt(target);
};

/**
 * aes加密
 */
export function Encrypt (word, keys) {
  let key = CryptoJS.enc.Utf8.parse(keys);
  let iv = CryptoJS.enc.Utf8.parse(keys);
  let encrypted = '';
  if (typeof (word) === 'string') {
    let srcs = CryptoJS.enc.Utf8.parse(word);
    encrypted = CryptoJS.AES.encrypt(srcs, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
  } else if (typeof (word) === 'object') { // 对象格式的转成json字符串
    let data = JSON.stringify(word);
    let srcs = CryptoJS.enc.Utf8.parse(data);
    encrypted = CryptoJS.AES.encrypt(srcs, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
  }
  return encrypted.toString();
}

/**
 * aes解密
 */
export function Decrypt (word, keys) {
  var key = CryptoJS.enc.Utf8.parse(keys);

  var iv = CryptoJS.enc.Utf8.parse(keys);
  var decrypt = CryptoJS.AES.decrypt(word, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });

  var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);

  return JSON.parse(decryptedStr.toString());
}

/**
 * 转换为string类型
 */
// export function inputString(v) {
//   for (let e in v) {
//     // console.log(typeof v[e])
//     if (typeof v[e] != 'object' && typeof v[e] != 'Array') {
//       v[e] = String(v[e])
//     } else {
//       inputString(v[e])
//     }
//   }
//   // console.log(v)
//   return v
// }

/**
 * 时间转换为时间戳
 */
export function toTimestamp (v) {
  return Date.parse(v) / 1000;
}
/**
 * 时间戳转换为时间
 */
export function toTime (v) {
  return new Date(parseInt(v) * 1000).toLocaleString().substr(0, 17);
}
/**
 * 生成guid
 */
export const GUID = () => {
  var s = [];
  var hexDigits = '0123456789abcdef';
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-';
 
  var uuid = s.join('');
  return uuid;
};
// 查找产品相等，添加
export function findProdAdd (array, x) {
  var len = array.length;

    
  var pos = 0;
  // console.log("this.datas::",array)
  // console.log("this.x::",x)
  // console.log("this.len::",len,pos)
  while (pos < len) {
    if (array[pos].ProdId === x.ProdId) { // 未找到就退出循环完成搜索
      // console.log(array[pos])
      // console.log(x)
      array[pos].Count = array[pos].Count + x.Count;
      array[pos].Money = array[pos].DiscountPrice * array[pos].Count;
      break;
    }
    pos += 1; // 并从下个位置开始搜索
  }
  if (pos === len) {
    array.push(x);
  }
  // console.log("this.datas:1:",array)
  return array;
}
// 查找产品相等，修改
export function findProdEdit (array, x) {
  var len = array.length;

    
  var pos = 0;
  while (pos < len) {
    if (array[pos].ProdId === x.ProdId) { // 未找到就退出循环完成搜索
      array[pos].Count = array[pos].Count;
      array[pos].Money = array[pos].DiscountPrice * array[pos].Count;
      break;
    }
    pos += 1; // 并从下个位置开始搜索
  }
  return array;
}
// 不绑定获取对象数据值
export function getData (data) {
  var obj = {};
  obj = JSON.parse(JSON.stringify(data)); // this.templateData是父组件传递的对象
  return obj;
}

// 判断参数是否是其中之一
export function oneOf (value, validList) {
  for (let i = 0; i < validList.length; i++) {
    if (value === validList[i]) {
      return true;
    }
  }
  return false;
}

/**
 * 检测参数的数据类型
 * @param {带检测类型的参数} obj 
 */
function typeOf (obj) {
  const toString = Object.prototype.toString;
  const map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  };
  return map[toString.call(obj)];
}

/**
 * 深度拷贝对象
 * @param {data} data 
 */
export function deepCopy (data) {
  const t = typeOf(data);
  let o;

  if (t === 'array') {
    o = [];
  } else if (t === 'object') {
    o = {};
  } else {
    return data;
  }

  if (t === 'array') {
    for (let i = 0; i < data.length; i++) {
      o.push(deepCopy(data[i]));
    }
  } else if (t === 'object') {
    for (let i in data) {
      o[i] = deepCopy(data[i]);
    }
  }
  return o;
}

/**
 * 检查目标Object数组的key值是否等于event， 如果有一个符合即返回true
 * @param {目标Object数组} array 
 * @param {Object key值} key 
 * @param {检测的参数} event 
 */
export function checkAccess (array, key, event) {
  let flag = false;
  if (Array.isArray(array)) {
    for (let i = 0; i < array.length; i++) {
      if (array[i][key] === event) {
        flag = true;
        break;
      }
    }
    return flag;
  }
  return flag;
}

/**
 * 新建一个api查询参数
 */
export function newApiParams () {
  return {
    searchKey: '', // 过滤关键字，预留，暂未使用， String
    pagesize: 0, // sql limit 关键字, 分页查询使用 Number
    page: 0, // sql offset 关键字, 分页查询使用 Number
    sortby: [], // sql 排序关键字， eg. seq  Array [String, String ...]
    order: [], // sql 排序关键字， eg. asc, desc 只能从这里个中获取，且和sortby对应  Array [String, String ...]
    fields: [], // 返回的字段 Array [String, String ...]
    query: {} // 其它查询条件, 如 Id = 1, 表示为 query.Id = 1
  };
}


export function sectionToChinese (section) {
  var chnNumChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  var chnUnitChar = ['', '十', '百', '千', '万', '亿', '万亿', '亿亿'];
  var strIns = ''; var chnStr = '';
  var unitPos = 0;
  var zero = true;
  while (section > 0) {
    var v = section % 10;
    if (v === 0) {
      if (!zero) {
        zero = true;
        chnStr = chnNumChar[v] + chnStr;
      }
    } else {
      zero = false;
      strIns = chnNumChar[v];
      strIns += chnUnitChar[unitPos];
      chnStr = strIns + chnStr;
    }
    unitPos++;
    section = Math.floor(section / 10);
  }
  return chnStr;
}
